package com.zcl.IO.objectStream;

import org.junit.Test;

import java.io.*;

/**
 * @Description:
 * @author: zcl
 * @date: 2022/3/15  15:07
 *
 * 对象流的使用:
 * 1.ObejctInputStream和ObjectOutputStream(不能序列化static和transient修饰的属性)
 * 2.作用:
 * 序列化: 把内存中的对象输出到文件中
 * 反序列化:把文件中的数据输入到程序中
 *
 * 3.要想java对象满足序列化的要求:
 *  1.Person类需要实现接口: Serializable
 *  2.当前类需要提供一个全局常量: private static final long serialVersionUID = 231654132135L;
 */
public class ObjectInputOutputStream {

    @Test
    public void objectInputOutputStreamTest(){
        //序列化过程: 将内存中的java对象保存到磁盘中或传输到网路节点中去
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream("src\\com\\zcl\\IO\\objectStream\\data.dat"));
            oos.writeObject(new String("哈哈哈哈哈哈啊哈哈哈"));
            oos.flush();//刷新操作
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } finally {
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        }
    }


    @Test
    public void testObjectInputStream(){
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream("src\\com\\zcl\\IO\\objectStream\\data.dat"));
            Object obj = ois.readObject();
            String str = (String) obj;
            System.out.println(str);
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        }
    }


    @Test
    public void objectInputOutputStreamPerson(){
        //序列化过程: 将内存中的java对象保存到磁盘中或传输到网路节点中去
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream("src\\com\\zcl\\IO\\objectStream\\Person.dat"));
            oos.writeObject(new Person("张小凡",18));
            oos.flush();//刷新操作
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } finally {
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        }
    }
}
